<template>
  <view class="bind-container">
    <!-- 固定头部区域 -->
    <view class="fixed-header">
      <!-- 顶部导航栏 -->
      <nav-bar title="合同绑定"></nav-bar>

      <!-- 标签切换栏 -->
      <view class="tab-bar">
        <view class="tab-item" :class="{ active: currentTab === 'pending' }" @click="switchTab('pending')">
          <span class="tab-text">待绑定</span>
        </view>
        <view class="tab-item" :class="{ active: currentTab === 'fixing' }" @click="switchTab('fixing')">
          <span class="tab-text">待修正</span>
        </view>
        <view class="tab-item" :class="{ active: currentTab === 'completed' }" @click="switchTab('completed')">
          <span class="tab-text">待完善</span>
        </view>
        <view class="contract-type">租客合同</view>
      </view>
    </view>
    <!-- swiper区域调整位置 -->
    <view class="content-wrapper">
      <!-- 使用swiper组件替换原来的scroll-view -->
      <swiper class="contract-swiper" :current="swiperIndex" @change="onSwiperChange" @transition="onSwiperTransition"
        @animationfinish="onAnimationFinish">
        <!-- 待绑定列表 -->
        <swiper-item>
          <scroll-view scroll-y class="contract-list" :show-scrollbar="false" :refresher-enabled="!isTransitioning"
            :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" @scrolltolower="loadMore">
            <view class="list-content">
              <empty-state v-if="tabData.pending.length === 0"></empty-state>
              <transition-group name="list-transition" tag="view" v-else>
                <contract-item v-for="(item, index) in tabData.pending" :key="index" :location="item.location"
                  :name="item.name" :phone="item.phone" :status="item.status" :status-type="'default'"
                  action-text="邀请绑定" action-type="default" @action="inviteBind(item)"></contract-item>
              </transition-group>
            </view>
            <!-- 底部加载更多提示 -->
            <uni-load-more :status="loadMoreStatus[currentTab]" v-if="tabData[currentTab].length > 0"></uni-load-more>
          </scroll-view>
        </swiper-item>

        <!-- 待修正列表 -->
        <swiper-item>
          <scroll-view scroll-y class="contract-list" :show-scrollbar="false" :refresher-enabled="!isTransitioning"
            :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" @scrolltolower="loadMore">
            <view class="list-content">
              <empty-state v-if="tabData.fixing.length === 0"></empty-state>
              <transition-group name="list-transition" tag="view" v-else>
                <contract-item v-for="(item, index) in tabData.fixing" :key="index" :location="item.location"
                  :name="item.name" :phone="item.phone" :status="item.status" status-type="fixing" action-text="去修正"
                  action-type="danger" @action="inviteBind(item)"></contract-item>
              </transition-group>
            </view>
            <!-- 底部加载更多提示 -->
            <uni-load-more :status="loadMoreStatus[currentTab]" v-if="tabData[currentTab].length > 0"></uni-load-more>
          </scroll-view>
        </swiper-item>

        <!-- 待完善列表 -->
        <swiper-item>
          <scroll-view scroll-y class="contract-list" :show-scrollbar="false" :refresher-enabled="!isTransitioning"
            :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" @scrolltolower="loadMore">
            <view class="list-content">
              <empty-state v-if="tabData.completed.length === 0"></empty-state>
              <transition-group name="list-transition" tag="view" v-else>
                <contract-item v-for="(item, index) in tabData.completed" :key="index" :location="item.location"
                  :name="item.name" :phone="item.phone" :status="item.status" :status-type="'default'"
                  action-text="邀请绑定" action-type="default" @action="inviteBind(item)"></contract-item>
              </transition-group>
            </view>
            <!-- 底部加载更多提示 -->
            <uni-load-more :status="loadMoreStatus[currentTab]" v-if="tabData[currentTab].length > 0"></uni-load-more>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script>
import ContractItem from '@/components/contract-item/index.vue';
import EmptyState from '@/components/empty-state/index.vue';
import NavBar from '@/components/nav-bar/index.vue';

export default {
  components: {
    ContractItem,
    EmptyState,
    NavBar
  },
  data() {
    return {
      pageData: {
        pending: { page: 1, loading: false },
        fixing: { page: 1, loading: false },
        completed: { page: 1, loading: false }
      },
      loadMoreStatus: {
        pending: 'more',
        fixing: 'more',
        completed: 'more'
      },
      page: 1,
      currentTab: 'pending',
      swiperIndex: 0, // 添加swiper索引
      isRefreshing: false,
      isTransitioning: false,
      contractList: [],
      tabData: {
        pending: [
          {
            location: '雄楚一号6号1单元703-3',
            name: '张亚红',
            phone: '13255889966',
            status: '将搬入'
          },
          {
            location: '柒零社区10号1单元501-5',
            name: '王永基',
            phone: '18501722317',
            status: '在租中'
          },
          {
            location: '尚文创业城6号1单元403-7',
            name: '张驰',
            phone: '17720481183',
            status: '将搬入'
          },
          {
            location: '创客广场1号1单元1207',
            name: '张毅',
            phone: '13599663322',
            status: '在租中'
          },
          {
            location: '蓝巢逸品B号2单元1101-C2',
            name: '陈昊',
            phone: '15236902743',
            status: '将搬入'
          },
          {
            location: '洪福家园2号1单元1802-3',
            name: '胡振东',
            phone: '15102734653',
            status: '在租中'
          },
          {
            location: '创客广场1号1单元1811',
            name: '张三',
            phone: '13899887766',
            status: '将搬入'
          }
        ],
        fixing: [
          {
            location: '光谷8号6号1单元612-楼下',
            name: '田宇丰',
            phone: '18501722317',
            status: '在租中'
          },
          {
            location: '光谷8号6号1单元612-楼上',
            name: '田宇丰',
            phone: '18501722317',
            status: '在租中'
          }
        ],
        completed: []
      }
    };
  },
  mounted() {
    this.loadContractList();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    showSearch() {
      uni.navigateTo({
        url: '/pages/contract/search'
      });
    },
    switchTab(tab) {
      this.currentTab = tab;
      // 根据tab设置swiper索引
      switch (tab) {
        case 'pending':
          this.swiperIndex = 0;
          break;
        case 'fixing':
          this.swiperIndex = 1;
          break;
        case 'completed':
          this.swiperIndex = 2;
          break;
      }
      // 切换标签时重置数据并加载
      this.resetAndLoad();
    },
    // 添加重置并加载方法
    resetAndLoad() {
      this.pageData[this.currentTab].page = 1;
      this.loadMoreStatus[this.currentTab] = 'more';
      this.contractList = [];
      this.loadContractList(true);
    },
    onSwiperTransition(e) {
      // 当 swiper 开始滑动时，设置 isTransitioning 为 true
      if (e.detail.dx !== 0) {
        this.isTransitioning = true;
      }
    },
    onAnimationFinish() {
      // 动画完全结束后，重置状态
      setTimeout(() => {
        this.isTransitioning = false;
      }, 500);
    },
    onSwiperChange(e) {
      // 根据swiper的切换更新当前tab
      const index = e.detail.current;
      const prevTab = this.currentTab;
      switch (index) {
        case 0:
          this.currentTab = 'pending';
          break;
        case 1:
          this.currentTab = 'fixing';
          break;
        case 2:
          this.currentTab = 'completed';
          break;
      }
      // 如果标签页发生变化，重置并加载新数据
      if (prevTab !== this.currentTab) {
        this.resetAndLoad();
      }
    },
    async loadContractList(isRefresh = false) {
      const currentStatus = this.pageData[this.currentTab];

      // 防止重复加载
      if (currentStatus.loading) return;
      currentStatus.loading = true;

      try {
        // 模拟接口调用
        await new Promise(resolve => setTimeout(resolve, 500));

        const pageSize = 5;
        const start = (currentStatus.page - 1) * pageSize;
        const end = currentStatus.page * pageSize;
        const currentList = this.tabData[this.currentTab];

        // 获取分页数据
        const pageData = currentList.slice(start, end);

        if (isRefresh) {
          // 刷新则替换数据
          this.contractList = pageData;
        } else {
          // 加载更多则追加数据
          this.contractList = [...this.contractList, ...pageData];
        }

        // 更新加载状态
        this.loadMoreStatus[this.currentTab] = end >= currentList.length ? 'noMore' : 'more';

      } catch (error) {
        // 处理错误情况
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        currentStatus.loading = false;
      }
    },
    async onRefresh() {
      this.isRefreshing = true;  // 添加刷新状态
      this.pageData[this.currentTab].page = 1;
      this.loadMoreStatus[this.currentTab] = 'more';
      await this.loadContractList(true);
      this.isRefreshing = false;  // 重置刷新状态
    },
    async loadMore() {
      if (this.loadMoreStatus[this.currentTab] !== 'more') return;

      this.loadMoreStatus[this.currentTab] = 'loading';
      this.pageData[this.currentTab].page++;
      await this.loadContractList();
    },
    inviteBind(item) {
      // 处理邀请绑定逻辑
      uni.showModal({
        title: '邀请绑定',
        content: `是否向${item.name}发送绑定邀请？`,
        success: (res) => {
          if (res.confirm) {
            // TODO: 实现邀请绑定接口调用
            uni.showToast({
              title: '邀请已发送',
              icon: 'success'
            });
          }
        }
      });
    },
    makePhoneCall(phone) {
      uni.makePhoneCall({
        phoneNumber: phone
      });
    }
  }
};
</script>

<style lang="scss">
.bind-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;

  .tab-bar {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx 80rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;

    .tab-item {
      position: relative;
      font-size: 28rpx;
      color: #333;
      flex: 1;
      text-align: center;

      .tab-text {
        position: relative;
        display: inline-block;
      }

      &.active {
        font-weight: 500;

        .tab-text::after {
          content: '';
          position: absolute;
          bottom: -20rpx;
          left: 0;
          width: 100%;
          height: 6rpx;
          background-color: #007AFF;
          border-radius: 3rpx;
        }
      }
    }

    .contract-type {
      position: absolute;
      left: 32rpx;
      bottom: 10rpx;
      font-size: 24rpx;
      color: #1890ff;
      z-index: 10;
      background-color: #e6f7ff;
      padding: 4rpx 10rpx;
      border-radius: 8rpx;
    }
  }

  .contract-list {
    height: 100%;
    box-sizing: border-box;
  }

  .list-content {
    padding: 30rpx 20rpx 20rpx;
    min-height: 100%;
    box-sizing: border-box;
  }

  .list-transition-enter-active,
  .list-transition-leave-active {
    transition: all 0.5s ease;
  }

  .list-transition-enter-from,
  .list-transition-leave-to {
    opacity: 0;
    transform: translateY(30px);
  }

  .list-transition-move {
    transition: transform 0.5s ease;
  }
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #fff;
  padding: 0 30rpx;
  position: relative;

  .nav-left {
    position: absolute;
    left: 30rpx;
    height: 100%;
    display: flex;
    align-items: center;
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
}

.content-wrapper {
  padding-top: 220rpx; // 为固定头部留出空间
  height: 100vh;
  box-sizing: border-box;
}

.contract-swiper {
  height: 100%;
  background-color: #f5f5f5;
}
</style>